﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Domain;

namespace WebRole1
{
	public partial class AddSubforum : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["Username"] != null)
				{
					if (aCookie["Username"].ToString() != "root")
					{
						Response.Redirect("index");
					}
				}
			}
			else
			{
				Response.Redirect("index");
			}


			if (!IsPostBack)
			{
				Services.ForumService forumServ = new Services.ForumService();

				IList<Forum> subforums = forumServ.getForums();
				gridSubforums.DataSource = subforums;
				gridSubforums.DataBind();

				Int64? subforumID = null;
				if (HttpContext.Current.Request.QueryString["id"] != null)
				{
					subforumID = Int64.Parse(HttpContext.Current.Request.QueryString["id"].ToString());

					foreach (Forum forum in subforums)
					{
						if (forum.ID == subforumID)
						{
							txtDescription.Text = forum.Description;
							txtForumTitle.Text = forum.Name;
						}
					}
				}
			}
		}


		protected void btnNew_Click(object sender, EventArgs e)
		{
			Response.Redirect("addsubforum.aspx");
		}

		protected void btnDelete_Click(object sender, EventArgs e)
		{
			Int64? subforumID = null;
			if (HttpContext.Current.Request.QueryString["id"] != null)
			{
				subforumID = Int64.Parse(HttpContext.Current.Request.QueryString["id"].ToString());
			}

			if (subforumID.HasValue)
			{
				Services.ForumService forumServ = new Services.ForumService();
				forumServ.DeleteSubforum(subforumID.Value);
			}

			Response.Redirect("addsubforum.aspx");
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			Int64? subforumID = null;
			if (HttpContext.Current.Request.QueryString["id"] != null)
			{
				subforumID = Int64.Parse(HttpContext.Current.Request.QueryString["id"].ToString());
			}


			Services.ForumService forumServ = new Services.ForumService();

			try
			{
				forumServ.InsertOrUpdateForum(subforumID, txtForumTitle.Text, txtDescription.Text);
				Response.Redirect("addsubforum.aspx");
			}
			catch (Exception ex)
			{
				throw ex;
			}

		}

	}
}